#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int splitFile(char *file_name, long fblock);
int combinationFile(char *file_list, char *file_name);

int main(int argc,char* argv[])
{
	char judge[2]="\0";
	char file_name[1024]="\0";
	char file_list[1024]="\0";
	long fblock=0;

	strcpy(judge,argv[2]);
	if(judge[0] == 's' || judge[0] == 'S')
	{
		strcpy(file_name,argv[3]);
		fblock = atoi(argv[4]);
		splitFile(file_name,fblock);
	}
	else if(judge[0] == 'c' || judge[0] == 'C')
	{
		strcpy(file_list, argv[3]);
		strcpy(file_name, argv[4]);
		combinationFile(file_list,file_name);
	}
	else
	{
		printf("wrong command!");
	}

	return 0;
}


int splitFile(char *file_name, long fblock)
{
	FILE *fpr;
	FILE *fpw;
	FILE *fpList;

	char newFile_name[1024]; 
	int file_id =1; 

	long offset; 
	long fsize;  
	char data;

	fpr = fopen(file_name,"rb");
	if(!fpr) {
		printf("fail to open file\n");
		exit(1);
	}
	fpList = fopen("fnameList.txt","w"); 

	fseek(fpr,0,SEEK_END); 
	fsize = ftell(fpr); 
	fseek(fpr,0,SEEK_SET); 

	sprintf(newFile_name,"%s.%03d",file_name,file_id); 
	fpw = fopen(newFile_name,"wb"); 
	fputs(strcat(newFile_name,"\n"), fpList);
	do {
		fread(&data,sizeof(char),1,fpr);
		fwrite(&data,sizeof(char),1,fpw); 
		offset = ftell(fpr);
		if(offset % fblock == 0) {
			fclose(fpw);
			file_id++;
			sprintf(newFile_name,"%s.%03d", file_name,file_id);
			fpw = fopen(newFile_name,"wb");
			fputs(strcat(newFile_name,"\n"), fpList);
		}
	}while(offset != fsize); 

	if(fpw) {
		fclose(fpw);
	}
	fclose(fpr);
	fclose(fpList);
	printf("file split finished\n");
	printf("have generate filename list:fnameList.txt\n");
	return 0;
}

int combinationFile(char *file_list, char *file_name)
{
	FILE *fpr;
	FILE *fpw;
	FILE *fplist;
	
	char fnametemp[1024];
	char data;
	unsigned int size_r; 
	fpw = fopen(file_name,"wb");
	if(!fpw) {
		printf("fial to create file\n");
		exit(1);
	}
	fplist = fopen(file_list,"r");
	if(!fplist) {
		printf("fail to open file\n");
		exit(1);
	}
	while(fgets(fnametemp,1024,fplist) != NULL) {
		fnametemp[strlen(fnametemp)-1]='\0';
		fpr = fopen(fnametemp,"rb");
		if(!fpr) {
			printf("opem file: %s fail\n",file_name);
			exit(1);
		}
		size_r = fread(&data,sizeof(char),1,fpr);
		while(size_r > 0) {
			fwrite(&data,sizeof(char),1,fpw);
			size_r = fread(&data,sizeof(char),1,fpr); 
		}
		fclose(fpr); 
	}
	fclose(fpw);
	fclose(fplist);
	printf("merge file finished\n");
	printf("have generated new file: %s\n",file_name);
	return 0;
}
